package com.zhao.customer.controller;


import com.google.code.kaptcha.Constants;
import com.zhao.customer.dao.UserDao;
import com.zhao.customer.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/update.do")
public class UpdateController extends HttpServlet {
    private UserDao ud = new UserDao();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        try {
            User user = ud.selectById(id);
            req.getSession().setAttribute("user", user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        resp.sendRedirect("update.jsp");//重定向的目的:防止表单重复提交
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        String name = req.getParameter("name");
        String password = req.getParameter("password");

        if ((!name.isEmpty() || !name.equals(" ")) && (!password.isEmpty() || !password.equals(" "))) {
            ud.update(new User(id, name, password));
            resp.sendRedirect("list.do");
        } else {
            resp.sendRedirect("update.jsp");
        }

    }
}
